<template>
  <!-- 需要传入一个class 来确定范围 -->
  <div ref="contentMenuBox" class="contentMenu">
    <slot></slot>
    <!-- 右键显示的内容 -->
    <div ref="list" class="list">
      <div
        v-for="(item, index) in props.menuList"
        :key="index"
        @click="choose(item)"
      >
        {{ item }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, defineProps, defineEmits, onUnmounted } from "vue";
const contentMenuBox = ref();
const list = ref();
const props = defineProps({
  menuList: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

onMounted(() => {
  contentMenuBox.value.addEventListener("contextmenu", (e) => {
    e.preventDefault();
    e.stopPropagation();
    list.value.style.top = `${e.pageY}px`;
    list.value.style.left = `${e.pageX}px`;
    list.value.style.display = "block";
  });
  window.addEventListener("mousedown", () => {
    list.value.style.display = "none";
  });
});
onUnmounted(() => {
  contentMenuBox.value.removeEventListener("mousedown");
  window.removeEventListener("mousedown", () => {});
});

const emit = defineEmits(["choose"]);
const choose = (item: String) => {
  emit("choose", item);
};
</script>

<style  scoped>
.contentMenu {
  display: flex;
  align-items: center;
}

.list {
  display: none;
  transition: 0.5s;
  width: 60px;
  height: 80px;
  position: absolute;
  background-color: wheat;
  box-shadow: 3px 1px 6px -1px black;
}
</style>